package cn.hysh.appium.util;

import java.util.ArrayList;
import java.util.List;

/**
 *  此类封装了appiumn server所需要的端口分配方法
 * */
public class Port {
    private DosCmd execDos;
    private Log logger = Log.getLogger(Port.class);
    public Port(DosCmd execDos){
        this.execDos = execDos;
    }

    /**
     *  验证端口是否被占用
     * */
    public Boolean isPortUsed(int portNum){
        List<String> portRes = new ArrayList<String>();
        String osName = System.getProperty("os.name");
        boolean flag = true;
        try {
            String command = "";
            if (osName.toLowerCase().contains("mac")){
                command = "netstat -an|grep " + portNum;
            }else if (osName.toLowerCase().contains("win")){
                command = "netstat -ano|findstr " + portNum;
            }
            portRes = execDos.execCmdConsole(command);
            System.out.println(portRes.size());
            if (portRes.size()>0){
                logger.debug(String.valueOf(portNum) + "端口已被占用了");
            }else{
                logger.debug(String.valueOf(portNum) + "端口没有被占用");
                flag=false;
            }
        } catch (Exception e) {
            logger.error(String.valueOf(portNum) + "获取端口占用状态失败！" + e);
        }
        return flag;
    }

    /**
     *  基于当前连接的设备数量生成可用的端口
     * */
    public List<Integer> GeneratPortList(int portStart, int deviceTotal){
        List<Integer> portList = new ArrayList<Integer>();
        int i = 0;
        while (portList.size() != deviceTotal){
            if (portStart >= 0 && portStart <=60000+i){
                portList.add(portStart);
            }
            portStart++;
            i++;
        }
        return portList;
    }

    public static void main(String[] args) throws Exception{
        Port p = new Port(new DosCmd());
        System.out.println(p.isPortUsed(4480));

        Servers server=new Servers(p, new DosCmd());
        List<String> udidList=server.getDevices();
        int count=udidList.size();
        List<Integer> portList=p.GeneratPortList(4491, count);
        for(Integer i:portList){
            System.out.println(i);
        }
        List<Integer> bpList=p.GeneratPortList(3678, count);
        for(Integer i:bpList){
            System.out.println(i);
        }
    }

}
